import java.util.ArrayList;
import java.util.List;

public class Test37_1 {
    public static void serialize(TreeNode root, List<Integer> res){
        List<TreeNode> list = new ArrayList<>();
        list.add(root);
        TreeNode node;
        //层序遍历
        while(list.size() > 0){
            node = list.remove(0);
            if (node == null) res.add(null);
            else {
                res.add(node.val);
                list.add(node.left);
                list.add(node.right);
            }
        }
    }


    public  static TreeNode  deserialize(List<Integer> res,int index){
        if (res.size() < 1 || index < 0 || res.size() <= index || res.get(index) == null) return null;
        TreeNode root = new TreeNode(res.get(index));
        root.left = deserialize(res,index*2+1);
        root.right = deserialize(res,index*2+2);
        return root;
    }


    public static void main(String[] args) {
        /*
        *                   1
        *           2               3
        *     4          5     6          7
        * */
        TreeNode root = new TreeNode();
        root.val = 1;
        root.left = new TreeNode();
        root.left.val = 2;
        root.right = new TreeNode();
        root.right.val = 3;
        root.left.left = new TreeNode();
        root.left.left.val = 4;
        root.left.right = new TreeNode();
        root.left.right.val = 5;
        root.right.left = new TreeNode();
        root.right.left.val = 6;
        root.right.right = new TreeNode();
        root.right.right.val = 7;

        List<Integer> list = new ArrayList<>();
        serialize(root,list);
        System.out.println(list);
        System.out.println();
        deserialize(list,0);
        print(root);
    }
    private static void print(TreeNode root) {
        if (root != null) {
            System.out.printf("%-3d", root.val);
            print(root.left);
            print(root.right);
        }
    }

}
